import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../../../common/api/x_cms_assemble_control.dart';
import '../../../../common/models/cms/cms_category_data.dart';
import '../../../../common/models/cms/document_data.dart';
import '../../../../common/utils/event_bus.dart';
import '../../../../common/utils/o2_api_manager.dart';
import '../../../../common/values/o2.dart';
import '../cms_category_picker/view.dart';
import '../cms_document/view.dart';
import '../cms_helper.dart';
import 'index.dart';

class CmsEditDocumentController extends GetxController {
  CmsEditDocumentController();

  final state = CmsEditDocumentState();
  
  final _eventBus = EventBus();
  final refreshController = RefreshController();
  int page = 1; // 分页查询
  bool isLoading = false; // 防止重复刷新

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
     _eventBus.on(EventBus.cmsCategoryDocListRefreshMsg, "cms_category_edit", (arg) { 
      onRefresh();
    });
    onRefresh();
    super.onReady();
  }
    @override
  void onClose() {
    _eventBus.off(EventBus.cmsCategoryDocListRefreshMsg, "cms_category_edit");
    super.onClose();
  }
 
  onRefresh() async {
    if (isLoading) return;
    page = 1;
    isLoading = true;
    loadDocList();
  }

  loadMoreData() async {
    if (isLoading) return;
    if (!state.hasMoreData) {
      refreshController.loadComplete();
      return;
    }
    isLoading = true;
    page++;
    loadDocList();
  }

  loadDocList() async {
    final me = O2ApiManager.instance.o2User?.distinguishedName;
    if (me == null) {
      isLoading = false;
      state.hasMoreData = false;
      refreshController.loadComplete();
      return;
    }
    Map<String, dynamic> data = {
      'creatorList': [me],
      'statusList': ['published', 'waitPublish', 'draft'],
      'orderField': 'createTime'
    };
    List<DocumentData>? list =
        await CmsAssembleControlService.to.getCmsDocumentListByPage(page, body: data);
    if (list != null) {
      if (page == 1) {
        state.docList.clear();
      }
      state.docList.addAll(list);
    }
    isLoading = false;
    state.hasMoreData = (list?.length ?? 0) == O2.o2DefaultPageSize;
    if (page == 1) {
      refreshController.refreshCompleted();
    } else {
      refreshController.loadComplete();
    }
  }

  clickPublish() async {
    final result = await CmsCategoryPickerPage.pick();
    if (result != null && result is CmsCategoryData) {
       CmsHelper().startCreateDocument(result);
    }
  }

  Future<void> clickEditDoc(DocumentData doc) async {
    await CmsDocumentPage.open(doc.id!, title: doc.title ?? '', options: {"readonly": false});
    onRefresh();
  }
}
